
package com.rd.p2p.app;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.*;

import javax.annotation.Resource;

import com.qdlc.p2p.dal.dto.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.borrowworker.BorrowHelper;
import com.qdlc.p2p.biz.borrowworker.worker.BaseBorrowWorker;
import com.qdlc.p2p.biz.processor.event.BorrowValueEvent;
import com.qdlc.p2p.biz.processor.task.collection.TenderTaskProcessor;
import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.biz.service.AwardSearchService;
import com.qdlc.p2p.biz.service.BorrowMortgageService;
import com.qdlc.p2p.biz.service.BorrowRepaymentService;
import com.qdlc.p2p.biz.service.BorrowService;
import com.qdlc.p2p.biz.service.BorrowTenderService;
import com.qdlc.p2p.biz.service.BorrowUploadService;
import com.qdlc.p2p.biz.service.ExperienceService;
import com.qdlc.p2p.biz.service.NewActivityPlanService;
import com.qdlc.p2p.biz.service.NewActivityRuleService;
import com.qdlc.p2p.biz.service.SystemConfigService;
import com.qdlc.p2p.biz.service.TppTenderLogService;
import com.qdlc.p2p.biz.service.UpRateService;
import com.qdlc.p2p.biz.service.UserBaseInfoService;
import com.qdlc.p2p.biz.service.UserCacheService;
import com.qdlc.p2p.biz.service.UserCertificationApplyService;
import com.qdlc.p2p.biz.service.UserCertificationService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.service.UserRedEnvelopeService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.service.UserStatisticsService;
import com.qdlc.p2p.biz.service.UserUploadService;
import com.qdlc.p2p.biz.service.VerifyLogService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.BorrowCategory;
import com.qdlc.p2p.common.constant.BorrowStatus;
import com.qdlc.p2p.common.constant.BorrowStyle;
import com.qdlc.p2p.common.constant.BorrowTimeType;
import com.qdlc.p2p.common.constant.BorrowType;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.constant.RedValidStatus;
import com.qdlc.p2p.common.constant.UserCacheStatus;
import com.qdlc.p2p.common.constant.UserType;
import com.qdlc.p2p.common.core.queue.QueueHandlers;
import com.qdlc.p2p.common.exception.BorrowException;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.BeanCopierUtils;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.common.util.BigDecimalUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.common.util.code.MD5;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dao.AccountDao;
import com.qdlc.p2p.dal.model.AccountModel;
import com.qdlc.p2p.dal.model.AppBorrowModel;
import com.qdlc.p2p.dal.model.AwardModel;
import com.qdlc.p2p.dal.model.BorrowModel;
import com.qdlc.p2p.dal.model.BorrowTenderModel;
import com.qdlc.p2p.dal.model.UserBaseInfoModel;
import com.qdlc.p2p.dal.model.UserCacheModel;
import com.qdlc.p2p.dal.model.UserCertificationApplyModel;
import com.qdlc.p2p.dal.model.UserIdentifyModel;
import com.qdlc.p2p.dal.util.UserUtils;
import com.rd.p2p.app.user.vo.BorrowTenderVO;

public class AppInvestAction extends BaseAction<BorrowModel> implements ModelDriven<BorrowModel> {

	@Resource
	private BorrowService borrowService;
	@Resource
	private BorrowTenderService borrowTenderService;
	@Resource
	private UserCertificationService userCertificationService;
	@Resource
	private UserCertificationApplyService userCertificationApplyService;
	@Resource
	private UserIdentifyService userIdentifyService;
	@Resource
	private AccountService accountService;
	@Resource
	private UserUploadService userUploadService;
	@Resource
	private BorrowMortgageService borrowMortgageService;
	@Resource
	private BorrowUploadService borrowUploadService;
	@Resource
	private UserCacheService userCacheService;
	@Resource
	private VerifyLogService verifyLogService;
	@Resource
	private BorrowRepaymentService borrowRepaymentService;
	@Resource
	private UserBaseInfoService userBaseInfoService;
	@Resource
	private UserStatisticsService userStatisticsService;
	@Resource
	private SystemConfigService systemConfigService;
	@Resource
	private ExperienceService experienceService;
	@Resource
	private UserRedEnvelopeService userRedEnvelopeService;
	@Resource
	private UserService userService;
	@Resource
	private TppTenderLogService tppTenderLogService;
	@Resource
	private NewActivityPlanService newActivityPlanService;
	@Resource
	private NewActivityRuleService newActivityRuleService;
	@Resource
	private AwardSearchService awardSearchService;
	private User user;
	private Map<String, Object> data;
	@Resource
	private UpRateService upRateService;


     /**
	 * 我要投资列表页（输出json字符串）---首页点击--我要投资--投资列表
	 * 
	 * @throws Exception
	 *             if has error
	 */

	@SuppressWarnings("static-access")
	@Action("/app/invest/investList")
	public void investJson() throws Exception {
		data = new HashMap<String, Object>();
		Borrow borrow = BorrowHelper.getWorker(model).prototype();
		model = model.instanceCurr(borrow, model);
		model.setScales(101); // 标记为不显示用户信息
		PageDataList<BorrowModel> list = borrowService.getList(model);
		data.put("data", list);
		data.put("nowTime", DateUtil.getNow());
		data.put("resCode", "1");
		user = getSessionUser();
		if (user != null) {
			data.put("useRedMoney", userRedEnvelopeService.userableCount(user.getUserId()) > 0);
			data.put("useUpRateMoney", upRateService.countRateInterest(user.getUserId()) > 0);
		}
		printWebJson(getStringOfJpaObj(data));
	}

	@Action("/app/invest/filmList")
	@SuppressWarnings("static-access")
	public void filmInvestJson() throws Exception {
		data = new HashMap<String, Object>();
		Borrow borrow = BorrowHelper.getWorker(model).prototype();
		model = model.instanceCurr(borrow, model);
		model.setScales(101); // 标记为不显示用户信息
		PageDataList<BorrowModel> list = borrowService.getList(model);

		if (list.getList().size() > 0) {
			for (int i = 0; i < list.getList().size(); i++) {
				BorrowModel borrowModel = list.getList().get(i);
				borrowModel.setPicurl(
						borrowUploadService.findPicByBorrowIdAndType(borrowModel.getId()).get(0).getPicPath());
			}
		}

		data.put("data", list);
		data.put("nowTime", DateUtil.getNow());
		data.put("url", SystemConfigHelper.getValue(SystemConfigHelper.Nid.IMAGE_SERVER_URL));
		data.put("resCode", "1");
		printWebJson(getStringOfJpaObj(data));
	}


/**
	 * 标详情JSON数据
	 * 
	 * @throws Exception
	 */

	@Action(value = "/app/invest/borrowDetail", interceptorRefs = { @InterceptorRef("globalStack") })
	public void borrowDetail() throws Exception {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		if (user == null) {
			printWebResCodeAndMsgResult("-1","用户尚未登录!");
			return;
		}
		String uuid = paramString("uuid");
		Borrow bw = borrowService.find(uuid);
		long borrowId = bw.getId();
		List<BorrowUpload> borrowUploads = borrowUploadService.findByBorrowId(borrowId);
		data.put("borrowUploads", borrowUploads);
		Borrow b = borrowService.findNotFlow(borrowId);

		List<UserUpload> userUploadlist = userUploadService.findByUser(b.getUser());
		data.put("userUploadlist", userUploadlist);
		UserCache userCache = userCacheService.findByUserId(b.getUser().getUserId());
		UserCacheModel uc = UserCacheModel.instance(userCache);
		String companyName = uc.getCompanyName();
		if ((companyName != null) && (companyName.length() > 5)) {
			uc.setCompanyName(companyName.substring(0, 2) + "****" + companyName.substring(companyName.length() - 4));
		}
		data.put("uc", uc);
		data.put("size", borrowUploadService.findByBorrowIdAndType(borrowId).size());
		double interest = (BigDecimalUtil.mul(b.getApr(), b.getTimeLimit()) * 100) / 30;
		PageDataList<BorrowTenderModel> list = borrowTenderService.list(b.getId(), this.model.getPage(), 999);
		BorrowModel borrow = BorrowModel.instance(b);
		VerifyLog log = verifyLogService.findByType(borrow.getId(), "borrow", 1);
		if (log != null) {
			borrow.setStartTime(DateUtil.dateStr2(log.getTime()));
		}
		String username = borrow.getUser().getUserName();
		String hideName = username.charAt(0) + "******" + username.charAt(username.length() - 1);
		borrow.setUserName(hideName);
		borrow.setUser(null);
		data.put("isDirectional", !StringUtil.isBlank(borrow.getPwd()));
		borrow.setPwd(null);
		data.put("borrow", borrow);
		// data.put("tenderToken", tenderToken);
		data.put("accountWait", BigDecimalUtil.sub(borrow.getAccount(), borrow.getAccountYes()));
		data.put("interest", BigDecimalUtil.round(interest));
		data.put("data", list);
		data.put("url", SystemConfigHelper.getValue(SystemConfigHelper.Nid.IMAGE_SERVER_URL));
		data.put("tenderUserCount", borrowService.getTenderUserCountByBorrowid(borrowId));

		// 判断用户是否允许投资新手包
		if (borrow.getCategory() != 1) {
			data.put("canTender", borrowTenderService.canTenderForCategory(user, 0));
		} else {
			data.put("canTender", Boolean.TRUE);
		}

		// 服务器当前时间，开标倒计时用
		data.put("serverNowTime", DateUtil.getNow());

		if (user != null) {
			UserIdentify userIdentify = userIdentifyService.findByUserId(getSessionUserId());
			UserIdentifyModel userIdentifyModel = UserIdentifyModel.instance(userIdentify);
			userIdentifyModel.setUserName(hideName);
			userIdentifyModel.setUser(null);
			data.put("userInvestIdentify", userIdentifyModel);
			data.put("payPwd", StringUtil.isBlank(user.getPayPwd()));
		}
		if (!"1".equals(paramString("borrowPreview"))) {
			data.put("userType", UserUtils.getUserCacheByUserId(user.getUserId()));
			Account account = accountService.findAccountByUserId(user.getUserId());
			AccountModel accountModel = AccountModel.instance(account);
			accountModel.setUser(null);
			data.put("account", accountModel);
			data.put("borrowPreview", 2);// 代表非后台预览标
		}
		List<UserCertificationApplyModel> certificationApply = userCertificationApplyService.findByUser(b.getUser());
		data.put("certificationApply", certificationApply);
		data.put("content", "aaaaa");
		data.put("resCode", "1");
		data.put("repayTime", new BaseBorrowWorker(bw, null).getRepayTime(bw.getPeriod()));
		// 借款人信息
		UserBaseInfo userBaseInfo = userBaseInfoService.findByUserId(b.getUser().getUserId());
		if (userBaseInfo != null) {
			UserBaseInfoModel userBaseInfoModel = UserBaseInfoModel.instance(userBaseInfo);
			userBaseInfoModel.setUser(null); // 防止前台查看用户信息
			data.put("userBaseInfo", userBaseInfoModel);
		}
		if (borrow.getType() == BorrowType.TYPE_OFFVOUCH) {
			AwardModel awardModel = awardSearchService.firstTender(borrow.getId());
			if (null != awardModel) {
				data.put("firstTender", awardModel);
			}
			if ((borrow.getStatus() == 3) || (borrow.getStatus() == 6) || (borrow.getStatus() == 7)
					|| (borrow.getStatus() == 8)) {
				data.put("lastTender", awardSearchService.lastTender(borrow.getId()));
				data.put("mostTender", awardSearchService.mostTender(borrow.getId()));
			}
		}
		printWebJson(getStringOfJpaObj(data));
	}


     /**
	 * 投标
	 * 
	 * @throws IOException
	 * 
	 * @throws Exception
	 *             if has error
	 */

	@SuppressWarnings("unchecked")
	@Action(value = "/app/invest/tender", interceptorRefs = { @InterceptorRef("globalStack") })
	public void tender() throws IOException {
		data = new HashMap<String, Object>();
		try {
			user = getSessionUser();
			if (user == null) {
				printWebResCodeAndMsgResult("-1","用户尚未登录!");
				return;
			}
			long userId = getSessionUserId(); // 用户ID
			User tenderUser = userService.find(userId); // 不从Session取 防止Session中用户不是最新的
			UserIdentify userIdentify = userIdentifyService.findByUserId(userId);

			String uuid = paramString("uuid");
			Borrow borrow = null;
			if (StringUtil.isBlank(uuid) || ((borrow = borrowService.find(uuid)) == null)) {
				printWebResCodeAndMsgResult("0","标信息不存在!");
				return;
			}

			BorrowModel borrowModel = BorrowModel.instance(borrow);

			// 设置用户输入的信息
			borrowModel.setMoney(this.model.getMoney());
			borrowModel.setPayPwd(this.model.getPayPwd());
			borrowModel.setInPwd(this.model.getPwd());

			// 校验用户认证状态及用户类型
			model.checkUser(userIdentify, UserUtils.getUserCacheByUserId(tenderUser));

			// 有定向密码则校验定向密码
			if (StringUtil.isNotBlank(borrow.getPwd()) && !model.getInPwd().equals(borrow.getPwd())) {
				throw new BorrowException("定向标密码不正确!", BorrowException.TYPE_CLOSE);
			}
			// 生成投标标记
			String resultFlag = System.currentTimeMillis() + "" + Math.random() * 10000;
			borrowModel.setTenderResultFlg(resultFlag);
			switch (borrowModel.getCategory()) {
				case BorrowCategory.EXPERIENCE: // 体验标
					borrowModel.setExperiences(this.model.getExperiences());
					checkTender(borrowModel, tenderUser, true);
					tenderExperience(borrowModel, tenderUser);
					break;
				default:
					checkTender(borrowModel, tenderUser, false);
					tenderCustom(borrowModel, tenderUser);
					break;
			}
			printWebResCodeAndMsgResult("1","投标成功!");
		} catch (Exception ex) {
			printWebResCodeAndMsgResult("0", ex.getMessage());
		}
	}

     /**
	 * 投标记录详细
	 * 
	 * @return String
	 * @throws Exception
	 *             if has error
	 */
	@Action("/app/user/detailTenderForJson")
	public void detailTenderForJson() throws Exception {
		AppBorrowModel appBorrowModel = new AppBorrowModel();
		data = appBorrowModel.validParam();
		if (StringUtil.isBlank(data)) {
			data = new HashMap<String, Object>();
			PageDataList<BorrowTenderModel> list = borrowTenderService.list(model.getBorrowId(), model.getPage(), 0);
			data.put("data", list);
			data.put("resCode", "1");
			printWebJson(getStringOfJpaObj(data));
		} else {
			printWebJson(getStringOfJpaObj(data));
		}
	}

	/**
	 * 投标前验证
	 *
	 * @param borrowModel  投标信息
	 * @param tenderUser   投标用户信息
	 * @param isExperience 是否体验标
	 */
	private void checkTender(BorrowModel borrowModel, User tenderUser, boolean isExperience) {

		long userId = tenderUser.getUserId();

		UserCache userCache = UserUtils.getUserCacheByUserId(tenderUser);

		// 返回地址
		String redirectUrl = "/invest/" + borrowModel.getUuid() + "/detail.html";

		if (StringUtil.isBlank(borrowModel.getPayPwd())) {
			throw new BorrowException("交易密码不能为空!", redirectUrl);
		}

		if (!MD5.encode(borrowModel.getPayPwd()).equals(tenderUser.getPayPwd())) {
			throw new BorrowException("交易密码不正确!", redirectUrl);
		}

		// 借款人需处理完借款才能投标
		if (userCache.getUserType() == UserType.INVESTMENT_BORROWER && !borrowService.checkUserBorrowList(userId)) {
			throw new BorrowException("您还有未完成的借款!", redirectUrl);
		}

		if (userCache.getStatus() == UserCacheStatus.LOCK) {
			throw new BorrowException("您账号已经被锁定,不能进行投标!", redirectUrl);
		}

		if (borrowModel.getFixedTime() != null && DateUtil.getNow().before(borrowModel.getFixedTime())) {
			throw new BorrowException("还未开标,无法投标!", redirectUrl);
		}

		// 初审通过的标 才能投
		if (borrowModel.getStatus() != BorrowStatus.STATUS_TRIAL_PASSED) {
			throw new BorrowException("该标还未审批,不能进行投标!", redirectUrl);
		}

		if (borrowModel.getUser().getUserId() == userId) {
			throw new BorrowException("您不能投自己发布的标!", redirectUrl);
		}

		// 体验标校验
		if (isExperience) {
			// 体验券必须
			long[] experienceIds = borrowModel.getExperiences();
			if (experienceIds == null) {
				throw new BorrowException("投标失败,请选择一张体验券!", redirectUrl);
			}

			// 体验金金额校验
			if (experienceIds.length > 1) {
				throw new BorrowException("投标失败,只能使用一张体验券!", redirectUrl);
			}

			// 查询并设置体验金金额
			double totalExperienceMoney = experienceService.sumAmount(experienceIds, userId);
			borrowModel.setTotalExperienceMoney(totalExperienceMoney);
			if (totalExperienceMoney <= 0) {
				throw new BorrowException("投标失败,请正确使用体验券!", redirectUrl);
			}

			// 该体验券是否已经被使用
			if (!experienceService.checkExperience(experienceIds, tenderUser)) {
				throw new BusinessException("投标失败,该笔投标包含已被使用的体验券!", redirectUrl);
			}

			// 该体验标还款方式不正确
			if (borrowModel.getBorrowTimeType() != BorrowTimeType.DAY || borrowModel.getStyle() != BorrowStyle.STYLE_ONETIME_REPAYMENT) {
				throw new BorrowException("该体验标的还款方式设置错误!请联系管理员!", redirectUrl);
			}
		} else {

			AccountDao accountDao = (AccountDao) BeanUtil.getBean("accountDao");
			Account account = accountDao.findByUserId(tenderUser.getUserId());

			// 实际支付金额
			double actualTenderMoney = borrowModel.getMoney();
			if (actualTenderMoney <= 0) {
				throw new BorrowException("实际支付金额不能少于1元!", redirectUrl);
			}

			if (actualTenderMoney > account.getUseMoney()) {
				throw new BorrowException("您的可用余额不足!", redirectUrl);
			}

			double tenderTotalAmount = borrowModel.getAccount();// 标的总额
			double tenderYesAmount = borrowModel.getAccountYes();// 已投金额
			if (tenderYesAmount >= tenderTotalAmount) {
				throw new BorrowException("该标已满!", redirectUrl);
			}

			// 可投金额
			double canTenderAmount = BigDecimalUtil.sub(tenderTotalAmount, tenderYesAmount);
			// 投标金额不得大于 可投金额
			if (actualTenderMoney > canTenderAmount) {
				throw new BorrowException("已超标,请刷新页面,重新修改投资金额!", redirectUrl);
			}

			// 最小投标金额
			double tenderLowestAmount = borrowModel.getLowestAccount();
			// 可投金额 >= 最小投标额 校验最小投标金额
			if (canTenderAmount >= tenderLowestAmount && tenderLowestAmount > 0) {
				// 投标金额不得小于最小投标金额
				if (actualTenderMoney < tenderLowestAmount) {
					throw new BorrowException(MessageFormat.format("投标金额不能小于单笔最小投标金额￥{0}元!", tenderLowestAmount), redirectUrl);
				}
			}

  /*          // 第三方可用余额 大于 投标金额 不允许投标
            String tppUserCustId = UserUtils.getUserTppCustId(tenderUser.getUserId());
            QueryBalanceResponse queryBalanceResponse = sinaPayService.queryBalance(tppUserCustId);
            if (actualTenderMoney > queryBalanceResponse.getAvailableBalance()) {
                throw new BorrowException("您的托管资金还存在未处理记录,请耐心等待!", redirectUrl);
            }
*/
			// 单笔最大投标金额
			double mostSingleAccountNum = borrowModel.getMostSingleLimit();
			if (mostSingleAccountNum > 0 && actualTenderMoney > mostSingleAccountNum) {
				throw new BorrowException(MessageFormat.format("投标金额不能大于单笔最大投标总额￥{0}元!", mostSingleAccountNum), redirectUrl);
			}

			// 累积最大投标金额
			double mostTenderMoney = borrowModel.getMostAccount();
			if (mostTenderMoney > 0) {
				// 该用户已经投标的金额
				double hasTenderMoney = borrowTenderService.hasTenderTotalPerBorrowByUserid(borrowModel.getId(), tenderUser.getUserId());
				// 剩余可投金额（最大投标金额 - 已投金额）
				double remainderCanMostTenderMoney = mostTenderMoney - hasTenderMoney;
				if (remainderCanMostTenderMoney == 0) {
					throw new BorrowException(MessageFormat.format("您对该标的投标金额已达到最大投标总额￥{0},无法继续投标!", mostTenderMoney), redirectUrl);
				}
				// 实际投标 > 剩余可投金额
				if (actualTenderMoney > remainderCanMostTenderMoney) {
					throw new BorrowException(MessageFormat.format("您对该标的投标金额不能大于最大累积投标额,您当前还可以投￥{0}元", remainderCanMostTenderMoney), redirectUrl);
				}
			}

			// 红包使用规则校验
			String redPacketsUseRule = SystemConfigHelper.getValue(SystemConfigHelper.Nid.RED_PACKETS_RULE);
			if (SystemConfigHelper.getStatus(SystemConfigHelper.Nid.RED_PACKETS_RULE) == RedValidStatus.CAN_USE && !StringUtil.isBlank(redPacketsUseRule)) {// 规则是否启用
				double totalRedEnvelopeMoney = borrowModel.getTotalRedEnvelopeMoney();// 使用红包总额
				String redPacketsRuleList[] = redPacketsUseRule.split(",");
				for (int i = 0; i < redPacketsRuleList.length; i++) {
					String redPacketsRules[] = redPacketsRuleList[i].split("\\^");
					if (redPacketsRules.length < 3) {
						throw new BorrowException("红包使用异常,请联系客服!", redirectUrl);
					}
					double canUseLowerLimit = Double.parseDouble(redPacketsRules[0]);
					double canUseUpperLimit = Double.parseDouble(redPacketsRules[1]);
					double canUseRedPacket = Double.parseDouble(redPacketsRules[2]);
					if (canUseLowerLimit < actualTenderMoney && actualTenderMoney <= canUseUpperLimit) {
						if (totalRedEnvelopeMoney > canUseRedPacket) {
							throw new BorrowException(MessageFormat.format("您当前投标金额只能使用包含￥{0}元以下的红包！", canUseRedPacket), redirectUrl);
						}
					}
					if (i == redPacketsRuleList.length - 1 && canUseUpperLimit < actualTenderMoney) {// 校验范围以外的情况,不能超出红包允许最大范围
						if (totalRedEnvelopeMoney > canUseRedPacket) {
							throw new BorrowException(MessageFormat.format("您当前投标金额只能使用包含￥{0}元以下的红包！", canUseRedPacket), redirectUrl);
						}
					}
				}
			}
		}
	}


	/**
	 * 投体验标
	 */
	private void tenderExperience(BorrowModel borrowModel, User tenderUser) {
		double tenderAmount = experienceService.sumAmount(this.model.getExperiences(), tenderUser.getUserId());
		borrowModel.setMoney(tenderAmount); // 投标金额
		// 投标放入队列中处理
		putQueue(borrowModel, tenderUser);
		request.setAttribute("tender", null);
	}


	private void putQueue(BorrowModel model, User tenderUser) {
		// 投标放入队列中
		BorrowValueEvent event = new BorrowValueEvent();
		event.setBorrowModel(model);
		event.setTaskProcessorClass(TenderTaskProcessor.class);
		event.setResultFlag(model.getTenderResultFlg());
		event.setUser(tenderUser);
		event.setClientIp(Global.getIP());
		//将事件放入到队列中
		QueueHandlers.put(event);
	}

	/**
	 * 投普通标
	 */
	private void tenderCustom(BorrowModel borrowModel, User tenderUser) {
		// 封装用户扩展参数
		Map map = new HashMap<String, Object>();
		long[] redIds = this.model.getRedEnvelopeIds();
		map.put("redIds", redIds[0] == 0 ? null : redIds); // 红包IDS
		map.put("type", borrowModel.getType()); // 标的类型
		map.put("uuid", borrowModel.getUuid()); // 标ID
		map.put("tppUserCustId", UserUtils.getUserTppCustId(tenderUser.getUserId())); // 用户新浪标识ID

		long rateInterestId = this.model.getRateInterestId();
		map.put("rateId", rateInterestId == 0 ? null : rateInterestId); // 加息券ID
		borrowModel.setParam(JSON.toJSONString(map));

		// 投标放入队列中处理
		putQueue(borrowModel, tenderUser);
		request.setAttribute("tender", null);
	}

	/**
	 * 获取某个标的投资记录
	 *
	 * @throws Exception
	 */
	@Action(value = "/app/invest/investorList", interceptorRefs = { @InterceptorRef("globalStack") })
	public void borrowDetailInvestorList() throws Exception {
		user = getSessionUser();
		data = new HashMap<String, Object>();
		if (user == null) {
			printWebResCodeAndMsgResult("-1","用户尚未登录!");
			return;
		}
		String uuid = paramString("uuid");
		int page = paramInt("page");
		int rows = paramInt("rows");
		Borrow bw = borrowService.find(uuid);
		if(null==bw){
			printWebResCodeAndMsgResult("0","暂无此标!");
			return;
		}
		long borrowId = bw.getId();
		Borrow b = borrowService.findNotFlow(borrowId);
		PageDataList<BorrowTenderModel> list = borrowTenderService.listInvestor(b.getId(),page,rows );
		PageDataList<BorrowTenderVO> voPageList = new PageDataList<BorrowTenderVO>();
		List<BorrowTenderModel> borrowTenderList = list.getList();
		List<BorrowTenderVO> voList = new ArrayList<BorrowTenderVO>();
		for (BorrowTenderModel borrowTenderModel : borrowTenderList) {
			BorrowTenderVO vo =new BorrowTenderVO();
			BeanCopierUtils.copyProperties(vo, borrowTenderModel);
			voList.add(vo);
		}
		voPageList.setList(voList);
		voPageList.setPage(list.getPage());
		voPageList.setType(list.getType());
		data.put("list",voPageList);
		data.put("tenderUserCount", borrowService.getTenderUserCountByBorrowid(borrowId));
		data.put("category",bw.getCategory());
		printWebJson(getStringOfJpaObj(data));
	}

	/**
	 * app投资规则
	 *
	 * @return String
	 * @throws Exception
	 *             if has error
	 */
	@Action("/app/invest/investRule")
	public void investRule() throws Exception {
		data = new HashMap<String, Object>();
		user = getSessionUser();
		if(null==user){
			printWebResCodeAndMsgResult("-1","用户尚未登陆");
			return;
		}
		//是否可使用红包
		boolean canUseRedEnvelope = false;
		//是否可使用体验金
		boolean canUseExperience = false;
		//是否可使用加息卷
		boolean canUseRate = false ;
		if(StringUtils.isEmpty(model.getUuid())){
			printWebResCodeAndMsgResult("0","传参有误");
			return;
		}
		Borrow borrow = borrowService.find(model.getUuid());
		if(model.getMoney()==0.00&&borrow.getCategory()!=2){
			printWebResCodeAndMsgResult("0","请传入金额");
			return;
		}
		Account account = accountService.findAccountByUserId(user.getUserId());
		if(borrow ==null){
			printWebResCodeAndMsgResult("0","暂无标信息");
			return;
		}
		double useMoney = account.getUseMoney();
		double apr=borrow.getApr();
		int timeType = borrow.getBorrowTimeType();
		int timeLimit= borrow.getTimeLimit();
		int category = borrow.getCategory();
		if (category == 1) {
			canUseRedEnvelope =true;
			canUseRate=true;
		}
		double money=model.getMoney();
		if(timeType == 1 ){
			apr = apr/36500;
		}
		else{
			apr = apr/1200;
		}
		String redPacketsRule =  SystemConfigHelper.getValue(SystemConfigHelper.Nid.RED_PACKETS_RULE);
		double profit =BigDecimalUtil.mul(BigDecimalUtil.mul(apr,timeLimit),money);
		DecimalFormat df = new DecimalFormat("0.00");
		String profitStr = df.format(profit);

		data.put("redPacketsRule", redPacketsRule);
		data.put("useMoney",useMoney);
		data.put("accountWait", BigDecimalUtil.sub(borrow.getAccount(), borrow.getAccountYes())+"");
		data.put("canUseRedEnvelope", canUseRedEnvelope);
		data.put("canUseExperience", canUseExperience);
		data.put("canUseRate",canUseRate);
		data.put("timeType", timeType+"");
		data.put("timeLimit", timeLimit+"");
		data.put("profitStr", profitStr);
		printWebJson(getStringOfJpaObj(data));
		return;
	}

	/**
	 * app投资规则
	 *
	 * @return String
	 * @throws Exception
	 *             if has error
	 */
	@Action("/app/invest/validInPwd")
	public void validInPwd() throws Exception {
		user = getSessionUser();
		if(null==user){
			printWebResCodeAndMsgResult("-1","用户尚未登陆");
			return;
		}
		String inPwd = paramString("inPwd");
		String uuid = paramString("uuid");
		Borrow borrow =borrowService.find(uuid);
		if(StringUtils.isEmpty(borrow.getPwd())){
			printWebResCodeAndMsgResult("0","非定向标");
			return;
		}
		// 校验用户投标前基本参数
		if (!inPwd.equals(borrow.getPwd())) {
			printWebResCodeAndMsgResult("0","定向密码错误");
			return;
		}
		else{
			printWebResCodeAndMsgResult("1","定向密码正确");
			return;
		}
	}
}

